﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Reflection
Imports System.Threading

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ValidationProperty("SelectedDate"), ToolboxData("<{0}:datepicker runat=server></{0}:datepicker>")> _
    Public Class DatePicker
        Inherits CompositeControl

#Region "Declarations"
        Private _text As String
        Private CalLabel As Label
        Private CalImage As Image
        Private div As HtmlControls.HtmlGenericControl
        Private labelHidden As New HiddenField
        Dim _dateFormat As String
        Dim _timeFormat As String
        Dim _selectedDate As String = ""
        Dim _weekendstyle As String = "amothermonthday"
        Dim _weekdaystyle As String = "amothermonthday"
        Dim _monthstyle As String = "amcaltitle"
        Dim _calendarstyle As String = "amcalendar"
        Dim _selecteddaystyle As String = "amselectedday"
        Dim _currentdaystyle As String = "amcurrentday"
        Dim _dayheaderstyle As String = "amdayheader"
        Dim _currentmonthdaystyle As String = "amcurrentmonthday"
        Dim _othermonthdaystyle As String = "amothermonthday"
        Dim _calwidth As String = "150"
        Dim _calheight As String = "150"
        Dim _imageUrl As String = ""
        Dim _nullDate As String = "01/01/1900"
        Dim _imgNext As String
        Dim _imgPrev As String
        Dim _showTime As Boolean = False
        Dim _defaultTime As String = "08:00 AM"
        Dim _selectedTime As String = ""
        Dim _showDateBox As Boolean = True
        Dim _callbackFlag As String = String.Empty
        Private _timeRequired As Boolean = False
        Private cal As Globalization.Calendar
        Private dtFI As Globalization.DateTimeFormatInfo
        Private _relatedControl As String
        Private _isEndDate As Boolean
#End Region

#Region "Properties"
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property Text() As String
            Get
                Return _text
            End Get
            Set(ByVal Value As String)
                _text = Value
            End Set
        End Property
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property SelectedDate() As String
            Get
                If Not _selectedDate = "" Then
                    Try
                        If CDate(_selectedDate) <= CDate(Me.NullDate) Then
                            Return ""
                        Else
                            Return _selectedDate
                        End If
                    Catch ex As Exception
                        Return String.Empty
                    End Try

                Else
                    Return ""
                End If
            End Get

            Set(ByVal Value As String)
                _selectedDate = Value
            End Set
        End Property
        ''' <summary>
        ''' Default 1/1/1900.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property NullDate() As String
            Get
                Return _nullDate
            End Get

            Set(ByVal Value As String)
                _nullDate = Value
            End Set
        End Property
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CalendarWidth() As String
            Get
                Return _calwidth
            End Get

            Set(ByVal Value As String)
                _calwidth = Value
            End Set
        End Property
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CalendarHeight() As String
            Get
                Return _calheight
            End Get

            Set(ByVal Value As String)
                _calheight = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amDayHeader.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssDayHeaderStyle() As String
            Get
                Return _dayheaderstyle
            End Get

            Set(ByVal Value As String)
                _dayheaderstyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amOtherMonthDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssWeekendStyle() As String
            Get
                Return _weekendstyle
            End Get

            Set(ByVal Value As String)
                _weekendstyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amOtherMonthDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssWeekdayStyle() As String
            Get
                Return _weekdaystyle
            End Get

            Set(ByVal Value As String)
                _weekdaystyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amCalTitle.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssMonthStyle() As String
            Get
                Return _monthstyle
            End Get

            Set(ByVal Value As String)
                _monthstyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amCalendar.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssCalendarStyle() As String
            Get
                Return _calendarstyle
            End Get

            Set(ByVal Value As String)
                _calendarstyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amSelectedDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssSelectedDayStyle() As String
            Get
                Return _selecteddaystyle
            End Get

            Set(ByVal Value As String)
                _selecteddaystyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amCurrentDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssCurrentDayStyle() As String
            Get
                Return _currentdaystyle
            End Get

            Set(ByVal Value As String)
                _currentdaystyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amCurrentMonthDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssCurrentMonthDayStyle() As String
            Get
                Return _currentmonthdaystyle
            End Get

            Set(ByVal Value As String)
                _currentmonthdaystyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default amOtherMonthDay.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CssOtherMonthDayStyle() As String
            Get
                Return _othermonthdaystyle
            End Get

            Set(ByVal Value As String)
                _othermonthdaystyle = Value
            End Set
        End Property
        ''' <summary>
        ''' Default MM/dd/yyyy.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property DateFormat() As String
            Get
                If _dateFormat = "" Then
                    Return "MM/dd/yyyy"
                Else
                    Return _dateFormat
                End If
            End Get

            Set(ByVal Value As String)
                _dateFormat = Value
            End Set
        End Property
        ''' <summary>
        ''' Default MM/dd/yyyy.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property TimeFormat() As String
            Get
                If _dateFormat = "" Then
                    Return "h:nn tt"
                Else
                    Return _timeFormat
                End If
            End Get

            Set(ByVal Value As String)
                _timeFormat = Value
            End Set
        End Property
        ''' <summary>
        ''' URL to Calendar image if not using the built in one.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property ImageUrl() As String
            Get
                Return _imageUrl
            End Get

            Set(ByVal Value As String)
                _imageUrl = Value
            End Set
        End Property
        ''' <summary>
        ''' URL for the next month image if not using the built in one.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property ImgNext() As String
            Get
                Return _imgNext
            End Get

            Set(ByVal Value As String)
                _imgNext = Value
            End Set
        End Property
        ''' <summary>
        ''' URL for the previous month image if not using the built in one.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property ImgPrev() As String
            Get
                Return _imgPrev
            End Get

            Set(ByVal Value As String)
                _imgPrev = Value
            End Set
        End Property
        ''' <summary>
        ''' Option to display time in date picker
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property ShowTime() As Boolean
            Get
                Return _showTime
            End Get

            Set(ByVal Value As Boolean)
                _showTime = Value
            End Set
        End Property
        ''' <summary>
        ''' Default Time.
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property DefaultTime() As String
            Get
                Return _defaultTime
            End Get

            Set(ByVal Value As String)
                _defaultTime = Value
            End Set
        End Property
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property SelectedTime() As String
            Get
                If _selectedTime = "" Then
                    If SelectedDate = "" Then
                        Return _defaultTime
                    Else
                        If CDate(SelectedDate).Year = 1900 Then
                            Return String.Empty
                        Else
                            Return CDate(SelectedDate).ToString(TimeFormat)
                        End If

                    End If
                Else
                    Return _selectedTime
                End If


            End Get

            Set(ByVal Value As String)
                _selectedTime = Value
            End Set
        End Property

        ''' <summary>
        ''' Option to display Textbox in date picker
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property ShowDateBox() As Boolean
            Get
                Return _showDateBox
            End Get

            Set(ByVal Value As Boolean)
                _showDateBox = Value
            End Set
        End Property

        ''' <summary>
        ''' Option to get CallbackFlag control
        ''' </summary>
        <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property CallbackFlag() As String
            Get
                Return _callbackFlag
            End Get

            Set(ByVal Value As String)
                _callbackFlag = Value
            End Set
        End Property
        Public Property TimeRequired() As Boolean
            Get
                Return _timeRequired
            End Get
            Set(ByVal value As Boolean)
                _timeRequired = value
            End Set
        End Property
        Public Property RelatedControl() As String
            Get
                Return _relatedControl
            End Get
            Set(ByVal value As String)
                _relatedControl = value
            End Set
        End Property
        Public Property IsEndDate() As Boolean
            Get
                Return _isEndDate
            End Get
            Set(ByVal value As Boolean)
                _isEndDate = value
            End Set
        End Property
#End Region

#Region "Subs"
        Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
            Try
                Dim tmpDate As Date
                Try
                    If Me.SelectedDate = "" Then
                        tmpDate = Date.Now
                    Else
                        tmpDate = CDate(Me.SelectedDate)
                    End If
                Catch ex As Exception
                    tmpDate = Date.Now
                End Try


                Dim temp As String = Me.CssClass
                Me.CssClass = ""
                If temp = "" Then
                    temp = "ampicker"
                End If
                writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0")
                writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0")
                writer.AddAttribute(HtmlTextWriterAttribute.Width, Width.ToString)
                writer.RenderBeginTag(HtmlTextWriterTag.Table)
                writer.RenderBeginTag(HtmlTextWriterTag.Tr)
                If Not [Text] = "" Then
                    writer.AddAttribute(HtmlTextWriterAttribute.Style, "white-space:nowrap")
                    writer.RenderBeginTag(HtmlTextWriterTag.Td)
                    writer.Write([Text])
                    writer.RenderEndTag()
                End If
                writer.AddAttribute(HtmlTextWriterAttribute.Width, Width.ToString)
                writer.RenderBeginTag(HtmlTextWriterTag.Td)
                writer.AddAttribute("class", temp)
                writer.AddAttribute("id", Me.ClientID)
                writer.AddAttribute("name", Me.ClientID)
                writer.AddAttribute("onblur", "return window." & Me.ClientID & ".onblur(this);")
                writer.AddAttribute("onkeypress", "return window." & Me.ClientID & ".onlyDateChars(event);")
                'writer.AddAttribute("onkeydown", "return window." & Me.ClientID & ".KeyPress(event);")
                'writer.AddAttribute("onclick", "return window." & Me.ClientID & ".Click(event);showalert();")
                If Me.Enabled = False Then
                    writer.AddAttribute("disabled", "disabled")
                End If
                If ShowDateBox Then
                    writer.RenderBeginTag(HtmlTextWriterTag.Input)
                    writer.RenderEndTag()

                End If
                dtFI = Thread.CurrentThread.CurrentCulture.DateTimeFormat
                If Not String.IsNullOrEmpty(Me.SelectedDate) Then
                    Dim dte As Date = Date.Parse(Me.SelectedDate)
                    Me.SelectedDate = dte.ToString(dtFI.ShortDatePattern & " " & dtFI.ShortTimePattern)
                End If
                writer.AddAttribute("type", "hidden")
                writer.AddAttribute("id", "hid_" & Me.ClientID)
                writer.AddAttribute("name", "hid_" & Me.ClientID)
                writer.AddAttribute("value", Me.SelectedDate)
                writer.RenderBeginTag(HtmlTextWriterTag.Input)
                writer.RenderEndTag()
                writer.AddAttribute("id", "cal_" & Me.ClientID)
                writer.AddAttribute("style", "display:none;position:absolute;")
                writer.RenderBeginTag(HtmlTextWriterTag.Div)
                writer.RenderEndTag()
                writer.RenderEndTag()
                writer.RenderBeginTag(HtmlTextWriterTag.Td)
                If ImageUrl = String.Empty Then
                    ImageUrl = Page.ClientScript.GetWebResourceUrl(Me.GetType(), "calendar.gif")
                End If
                If Me.Enabled = True Then
                    writer.AddAttribute("src", ImageUrl)
                    writer.AddAttribute("onclick", "window." & Me.ClientID & ".Toggle(event);")
                    writer.AddAttribute("id", "img_" & Me.ClientID)
                    writer.RenderBeginTag(HtmlTextWriterTag.Img)
                    writer.RenderEndTag()
                End If
                writer.RenderEndTag()
                writer.RenderEndTag()
                writer.RenderEndTag()
                Dim str As New StringBuilder
                str.Append("<script type=""text/javascript"">")

                cal = New Globalization.GregorianCalendar
                If Not Thread.CurrentThread.CurrentCulture Is Nothing Then
                    cal = Thread.CurrentThread.CurrentCulture.Calendar
                End If
                Me.DateFormat = dtFI.ShortDatePattern
                Me.TimeFormat = dtFI.ShortTimePattern
                str.Append("window." & Me.ClientID & "=new asDatePicker('" & Me.ClientID & "');")
                str.Append("window." & Me.ClientID & ".Locale='" & Me.Context.Request.UserLanguages(0).Substring(0, 2).ToUpper & "';")
                str.Append("window." & Me.ClientID & ".SelectedDate='" & Me.SelectedDate & "';")
                str.Append("window." & Me.ClientID & ".Width='" & Me.CalendarWidth & "';")
                str.Append("window." & Me.ClientID & ".Height='" & Me.CalendarHeight & "';")
                str.Append("window." & Me.ClientID & ".DateFormat='" & dtFI.ShortDatePattern & "';")
                str.Append("window." & Me.ClientID & ".TimeFormat='" & dtFI.ShortTimePattern & "';")
                str.Append("window." & Me.ClientID & ".Year=" & tmpDate.Year & ";")
                str.Append("window." & Me.ClientID & ".Month=" & (tmpDate.Month - 1) & ";")
                str.Append("window." & Me.ClientID & ".Day=" & tmpDate.Day & ";")
                str.Append("window." & Me.ClientID & ".SelectedYear=" & tmpDate.Year & ";")
                str.Append("window." & Me.ClientID & ".SelectedMonth=" & (tmpDate.Month - 1) & ";")
                str.Append("window." & Me.ClientID & ".SelectedDay=" & tmpDate.Day & ";")
                str.Append("window." & Me.ClientID & ".ShowTime=" & Me.ShowTime.ToString.ToLower & ";")
                str.Append("window." & Me.ClientID & ".DefaultTime='" & Me.DefaultTime.ToString & "';")
                str.Append("window." & Me.ClientID & ".CallbackFlag='" & Me.CallbackFlag & "';")
                If Not String.IsNullOrEmpty(RelatedControl) Then
                    Dim ctl As Control = Me.Parent.FindControl(RelatedControl)
                    If ctl Is Nothing Then
                        ctl = Page.FindControl(RelatedControl)
                    End If
                    If ctl Is Nothing Then
                        RelatedControl = String.Empty
                    Else
                        RelatedControl = ctl.ClientID
                    End If
                End If
                str.Append("window." & Me.ClientID & ".linkedControl='" & RelatedControl & "';")
                If IsEndDate Then
                    str.Append("window." & Me.ClientID & ".isEndDate=true;")
                Else
                    str.Append("window." & Me.ClientID & ".isEndDate=false;")
                End If

                Dim sTime As String = String.Empty
                SelectedTime = tmpDate.ToString(TimeFormat)
                If ShowTime Then
                    If Not SelectedTime = "12:00 AM" Then
                        sTime = SelectedTime
                    End If
                    If TimeRequired Then
                        str.Append("window." & Me.ClientID & ".RequireTime=true;")
                    Else
                        str.Append("window." & Me.ClientID & ".RequireTime=false;")
                    End If
                Else
                    str.Append("window." & Me.ClientID & ".RequireTime=false;")
                End If

                str.Append("window." & Me.ClientID & ".SelectedTime='" & sTime & "';")
                If ImgNext = "" Then
                    str.Append("window." & Me.ClientID & ".ImgNext='" & Page.ClientScript.GetWebResourceUrl(Me.GetType, "cal_nextMonth.gif") & "';")
                Else
                    str.Append("window." & Me.ClientID & ".ImgNext='" & Page.ResolveUrl(ImgNext) & "';")
                End If
                If ImgPrev = "" Then
                    str.Append("window." & Me.ClientID & ".ImgPrev='" & Page.ClientScript.GetWebResourceUrl(Me.GetType, "cal_prevMonth.gif") & "';")
                Else
                    str.Append("window." & Me.ClientID & ".ImgPrev='" & Page.ResolveUrl(ImgPrev) & "';")
                End If
                If Not Me.SelectedDate = "" Then
                    Try
                        If ShowTime = False And sTime = String.Empty Then
                            str.Append("window." & Me.ClientID & ".textbox.value=new Date(" & tmpDate.Year & "," & (tmpDate.Month - 1) & "," & tmpDate.Day & ").formatDP('" & Me.DateFormat & "','" & Me.ClientID & "');")
                            str.Append("window." & Me.ClientID & ".dateSel = new Date(" & tmpDate.Year & "," & (tmpDate.Month - 1) & "," & tmpDate.Day & ",0,0,0,0);")
                        Else
                            str.Append("window." & Me.ClientID & ".textbox.value=new Date(" & tmpDate.Year & "," & (tmpDate.Month - 1) & "," & tmpDate.Day & "," & tmpDate.Hour & "," & tmpDate.Minute & ",0).formatDP('" & Me.DateFormat & " " & Me.TimeFormat & "','" & Me.ClientID & "');")
                            str.Append("window." & Me.ClientID & ".dateSel = new Date(" & tmpDate.Year & "," & (tmpDate.Month - 1) & "," & tmpDate.Day & "," & tmpDate.Hour & "," & tmpDate.Minute & ",0);")
                        End If
                    Catch ex As Exception

                    End Try

                End If
                Dim xMonths As Integer = cal.GetMonthsInYear(cal.GetYear(tmpDate), cal.GetEra(tmpDate))
                Dim currMonth As Integer = cal.GetMonth(tmpDate)
                Dim currYear As Integer = cal.GetYear(tmpDate)
                Dim currDay As Integer = cal.GetDayOfMonth(tmpDate)

                str.Append("window." & Me.ClientID & ".MonthDays = new Array(")
                For i As Integer = 0 To xMonths - 1
                    str.Append(cal.GetDaysInMonth(currYear, i + 1))
                    If i < (xMonths - 1) Then
                        str.Append(",")
                    End If
                Next
                str.Append(");")
                str.AppendLine()

                Dim mNames() As String = dtFI.MonthNames
                str.Append("window." & Me.ClientID & ".MonthNames = new Array(")
                For i As Integer = 0 To xMonths - 1

                    str.Append("'" & mNames(i) & "'")
                    If i < (xMonths - 1) Then
                        str.Append(",")
                    End If
                Next
                str.Append(");")
                str.AppendLine()
                str.Append("window." & Me.ClientID & ".ShortMonthNames = new Array(")
                Dim mAbbr() As String = dtFI.AbbreviatedMonthNames
                For i As Integer = 0 To xMonths - 1
                    str.Append("'" & mAbbr(i) & "'")
                    If i < (xMonths - 1) Then
                        str.Append(",")
                    End If
                Next
                str.Append(");")
                str.AppendLine()
                str.Append("window." & Me.ClientID & ".ShortDayNames = new Array(")
                Dim dAbbr() As String = dtFI.AbbreviatedDayNames
                For i As Integer = 0 To 6
                    str.Append("'" & dAbbr(i) & "'")
                    If i < 6 Then
                        str.Append(",")
                    End If
                Next
                str.Append(");")
                str.AppendLine()

                str.Append("window." & Me.ClientID & ".Class={")
                str.Append("CssCalendarStyle:'" & CssCalendarStyle & "',")
                str.Append("CssMonthStyle:'" & CssMonthStyle & "',")
                str.Append("CssWeekendStyle:'" & CssWeekendStyle & "',")
                str.Append("CssWeekdayStyle:'" & CssWeekdayStyle & "',")
                str.Append("CssSelectedDayStyle:'" & CssSelectedDayStyle & "',")
                str.Append("CssCurrentMonthDayStyle:'" & CssCurrentMonthDayStyle & "',")
                str.Append("CssOtherMonthDayStyle:'" & CssOtherMonthDayStyle & "',")
                str.Append("CssDayHeaderStyle:'" & CssDayHeaderStyle & "',")
                str.Append("CssCurrentDayStyle:'" & CssCurrentDayStyle & "'};")
                str.Append("window." & Me.ClientID & ".selectedDate=window." & Me.ClientID & ".textbox.value;")
                str.Append("window." & Me.ClientID & ".timeLabel='[RESX:Time]';")



                str.Append("</script>")
                writer.Write(str)
            Catch ex As Exception

            End Try
        End Sub

        Private Sub DatePicker_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        End Sub
        Private Sub Calendar_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.ClientScript.IsClientScriptIncludeRegistered("AMDatePicker") Then
#If DEBUG Then
                Page.ClientScript.RegisterClientScriptInclude("AMDatePicker", Page.ResolveUrl("~/DesktopModules/activeforums/customcontrols/resources/datepicker.js"))

#Else
                Page.ClientScript.RegisterClientScriptInclude("AMDatePicker", Page.ClientScript.GetWebResourceUrl(Me.GetType, "datepicker.js"))
#End If

            End If
            Try
                If Page.IsPostBack Then
                    Me.SelectedDate = Context.Request.Form(Me.ClientID)
                End If
            Catch ex As Exception
            End Try
        End Sub
#End Region

    End Class
End Namespace
